package com.polaris.live.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.StringUtils
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.adapter.recharge.RechargeActTimeAdapter
import com.polaris.live.common.constant.PagConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.common.util.ViewUtils
import com.polaris.live.constant.UserConst
import com.polaris.live.databinding.DialogRechargeActBinding
import com.polaris.live.manager.GooglePayManager
import com.polaris.live.net.payerService
import com.polaris.live.resp.back_resp.PayerRechargeDailyRewardsInfoVo
import com.polaris.live.resp.back_resp.PayerRechargeDailyRewardsPriceResp
import com.polaris.live.resp.go_resp.RechargeRewardsDailyRequest
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.playAsync

/**
 * 充值活动弹窗
 *
 * @author Created by 半仙 on 2024/7/16/016 14:49
 */
class RechargeActDialog(
    context: Context,
    private val payerData: PayerRechargeDailyRewardsPriceResp,
    private val viewModel: BaseViewModel,
    private val onShowNewRechargeAcCallback: () -> Unit,
) : CenterPopupView(context) {

    override fun getImplLayoutId() = R.layout.dialog_recharge_act

    private lateinit var mBinding: DialogRechargeActBinding

    private val mTimeAdapter by lazy { RechargeActTimeAdapter() }

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogRechargeActBinding.bind(popupImplView)

        mBinding.pagBottom.apply {
            path = PagConst.RECHARGE_ACTIVITY_BOTTOM
            setRepeatCount(-1)
            play()
        }
        mBinding.timeRecycler.adapter = mTimeAdapter

        initData()
        initListener()
    }

    @SuppressLint("SetTextI18n")
    private fun initData() {
        val listTime = payerData.dailyRewardsInfoVo
        mBinding.timeRecycler.layoutManager =
            GridLayoutManager(context, listTime.size, GridLayoutManager.VERTICAL, false)

        mTimeAdapter.setList(listTime)

        if (listTime.size > 3) {
            mTimeAdapter.setSize(14f)
        }
        mBinding.apply {
            shapeTvDiamond.text = " Diamond "
            shapeTvDiamondNum.text = " *${payerData.coin} "
            shapeTvTitle.text = " ${StringUtils.getString(string.top_up_to_get)} "
            shapeTvTitle2.text = " ${StringUtils.getString(string.how_diamonds, payerData.coin.toString())} "
            shapeTvAllNum.text = StringUtils.getString(string.all_get_diamonds, payerData.totalCoins.toString())
            tvRewardDetail1.text = "*${payerData.everyDayCoin}"
            tvRewardDetail2.text = "*${payerData.gameCoins}"
            tvRewardDetail3.text = "*${payerData.avatarFrameDays}Days"
            if (payerData.avatarFrame?.endsWith(PagConst.PAG) == true) {
                pagRewardItem.playAsync(lifecycleScope, payerData.avatarFrame) {
                    setRepeatCount(-1)
                    visibility = View.VISIBLE
                }
            } else {
                ivRewardItem.visibility = View.VISIBLE
                Glide.with(context).load(ImageUtils.imgPath(payerData.avatarFrame)).into(ivRewardItem)
            }
        }

        val stateItem = listTime.find { it.today.toBoolean() } ?: listTime.getOrNull(0) ?: return
        onBottomState(stateItem)

        val indexOfFirst = listTime.indexOfFirst { it.today.toBoolean() }.takeIf { it != -1 } ?: 0
        mTimeAdapter.setSelectPosition(indexOfFirst)
    }

    private fun initListener() {
        mTimeAdapter.setOnItemClickListener { _, _, position ->
            mTimeAdapter.setSelectPosition(position)
            onBottomState(mTimeAdapter.getItem(position))
        }

        mBinding.shapeTvBuyMoney.setOnSingleClickListener {
            val item = mTimeAdapter.getSelectItem()
            if (item.rewardsStatus == UN_RECEIVE && item.today.toBoolean()) {//点击领取
                viewModel.request(
                    { payerService.receiveRechargeAc(RechargeRewardsDailyRequest(payerData.payerRechargeRewardsType)) },
                    {
                        item.rewardsStatus = RECEIVED
                        onBottomState(item)
                        ToastGravity.showGravity(StringUtils.getString(string.today_reward_receive_success))
                        todayIsLast()
                    },
                    {
                        ToastGravity.showGravity(it.errorMsg)
                    })
            } else if (item.rewardsStatus == NOT_PURCHASED) {//点击充值
                ViewUtils.getTopActivity(context)?.apply {
                    GooglePayManager.buyShow(this,
                        payerData.priceId,
                        UserConst.From.UNKNOWN,
                        payerData.payerRechargeRewardsType,
                        price = payerData.price,
                        onSuccess = {
                            XPopup.Builder(context)
                                .isDestroyOnDismiss(true)
                                .asCustom(
                                    RechargeActSuccessDialog(
                                        context,
                                        payerData.coin,
                                        payerData.dailyRewardsInfoVo
                                    )
                                ).show()
                            ToastGravity.showGravity(StringUtils.getString(string.buy_success))
                            dismiss()
                        },
                        onFailure = { it ->
                            XPopup.Builder(context)
                                .isDestroyOnDismiss(true)
                                .asCustom(ChargeFailureDialog(context)).show()

                            it?.errorMsg?.let {
                                ToastGravity.showGravity(it)
                            }
                        })
                }
            }
        }
    }

    private fun todayIsLast() {
        val list = mTimeAdapter.data
        val item = list.getOrNull(list.size - 1) ?: return
        //如果领取到了最后一天了，则关闭弹窗，重新请求新的弹窗
        if (item.today.toBoolean() && item.rewardsStatus == RECEIVED) {
            onShowNewRechargeAcCallback.invoke()
            dismiss()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun onBottomState(stateItem: PayerRechargeDailyRewardsInfoVo) {
        mBinding.pagBottom.visibility = View.GONE
        mBinding.ivBottom.visibility = View.GONE
        when (stateItem.rewardsStatus) {
            UN_RECEIVE -> {//未领取
                //是今天
                if (stateItem.today.toBoolean()) {
                    mBinding.pagBottom.visibility = View.VISIBLE
                    mBinding.shapeTvBuyMoney.text = StringUtils.getString(string.receive)
                } else {//不是今天
                    mBinding.ivBottom.visibility = View.VISIBLE
                    mBinding.shapeTvBuyMoney.text =
                        "${
                            TimeUtils.millis2String(
                                stateItem.rewardsDate,
                                "MM/dd"
                            )
                        } ${StringUtils.getString(string.receive)}"
                }
            }

            NOT_PURCHASED -> {
                mBinding.pagBottom.visibility = View.VISIBLE
                mBinding.shapeTvBuyMoney.text = "${payerData.price}\$"
            }

            RECEIVED -> {
                mBinding.ivBottom.visibility = View.VISIBLE
                mBinding.shapeTvBuyMoney.text = StringUtils.getString(string.received_string)
            }

            Expired -> {
                mBinding.ivBottom.visibility = View.VISIBLE
                mBinding.shapeTvBuyMoney.text =
                    "${
                        TimeUtils.millis2String(
                            stateItem.rewardsDate,
                            "MM/dd"
                        )
                    } ${StringUtils.getString(string.receive)}"
            }
        }
    }

    override fun getMaxWidth() = ScreenUtils.getScreenWidth()

    companion object {

        const val UN_RECEIVE = 0            //未领取
        const val RECEIVED = 1              //已领取
        const val Expired = 2               //已过期
        const val NOT_PURCHASED = 3         //未购买
    }
}